<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>教务管理系统 - 用户管理</title>
    <link rel="stylesheet" href="/styles.css">
    <link rel="stylesheet" href="/moving.css">
    <link rel="stylesheet" href="/navbar.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<!-- 导航栏 -->
<div th:replace="navbar :: ~{*}" th:with="activeLink='user_manage'"></div>
<!-- 查询表单 -->
<div class="container">
    <div class="d-flex flex-wrap align-items-center justify-content-between mb-3">
        <!-- 查询表单 -->
        <div class="d-flex align-items-center gap-3">
            <div>
                <label for="userName" class="form-label">用户名</label>
                <input type="text" id="userName" name="userName" class="form-control" placeholder="请输入用户名">
            </div>
            <div>
                <label for="role" class="form-label">角色</label>
                <select id="role" name="role" class="form-select">
                    <option value="">请选择</option>
                    <option value="admin">超级管理员</option>
                    <option value="student">学生</option>
                    <option value="teacher">教师</option>
                </select>
            </div>
            <button type="button" id="searchBtn" class="btn btn-primary search-btn">
                <i class="fa fa-search me-2"></i>查询
            </button>
        </div>
    </div>

    <!-- 用户显示表单 -->
    <table id="userTable" class="table table-striped mt-4">
        <!-- 操作按钮（添加、批量删除、导出） -->
        <div class="d-flex gap-2">
            <button type="button" id="addBtn" class="btn btn-success add-btn">
                <i class="fa fa-plus me-2"></i>添加
            </button>
            <button type="button" id="batchDeleteBtn" class="btn btn-danger batch-delete-btn">
                <i class="fa fa-trash me-2"></i>批量删除
            </button>
            <button type="button" id="exportBtn" class="btn btn-info">
                <i class="fa fa-download me-2"></i>导出
            </button>
        </div>
        <thead>
        <tr>
            <th><input type="checkbox" id="selectAll"></th>
            <th>用户名</th>
            <th>是否锁定</th>
            <th>所属角色</th>
            <th>注册日期</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user : ${users}">
            <td><input type="checkbox" class="userCheckbox" th:value="${user.id}"></td>
            <td th:text="${user.userName}"></td>
            <td>
                <!-- 锁定状态开关 -->
                <div class="form-check form-switch">
                    <input type="checkbox" class="form-check-input lock-toggle"
                           th:id="${'lockToggle_' + user.id}"
                           th:data-id="${user.id}"
                           th:checked="${user.locked==1}">
                    <label class="form-check-label" th:for="${'lockToggle_' + user.id}"
                           th:text="${user.locked==1} ? '已锁定' : '未锁定'"></label>
                </div>
            </td>
            <td>
            <span th:each="userRole : ${user.userRoles}" th:text="${userRole.role.name}" th:unless="${userRole == null}" th:remove="tag">
                <span th:if="${!#lists.last(user.userRoles, userRole)}">、</span>
            </span>
                <span th:if="${#lists.isEmpty(user.userRoles)}">无角色</span>
            </td>
            <td th:text="${user.createdAt}"></td>
            <td>
                <a href="#" class="editIcon" th:data-id="${user.id}"><i class="bi bi-pencil"></i>修改</a>
                <a href="#" class="deleteIcon" th:data-id="${user.id}"><i class="bi bi-trash"></i>删除</a>
            </td>
        </tr>
        </tbody>
    </table>

    <!-- 分页导航 -->
    <div class="pagination-area d-flex justify-content-between align-items-center mt-3">
        <ul class="pagination">
            <li class="page-item">
                <a class="page-link" th:href="@{/system/manage(page=${currentPage - 1>0?currentPage - 1:1}, sortField=${sortField}, sortDirection=${sortDirection})}"
                   th:disabled="${!hasPrevious}">上一页</a>
            </li>
            <li class="page-item" th:each="i : ${#numbers.sequence(1, totalPages)}"
                th:classappend="${i == currentPage} ? 'active' : ''">
                <a class="page-link" th:href="@{/system/manage(page=${i}, sortField=${sortField}, sortDirection=${sortDirection})}"
                   th:classappend="${i == currentPage} ? 'active' : ''">[[${i}]]</a>
            </li>
            <li class="page-item">
                <a class="page-link" th:href="@{/system/manage(page=${currentPage + 1<totalPages?currentPage + 1:totalPages}, sortField=${sortField}, sortDirection=${sortDirection})}"
                   th:disabled="${!hasNext}">下一页</a>
            </li>
        </ul>
    </div>

</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label for="newUserName" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="newUserName" required>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">密码</label>
                        <input type="password" class="form-control" id="newPassword" required>
                    </div>
                    <div class="mb-3">
                        <label for="newSalt" class="form-label">盐值</label>
                        <input type="text" class="form-control" id="newSalt">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">是否锁定</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" id="newLocked">
                            <label class="form-check-label" for="newLocked" id="lockStatusLabel">未锁定</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="newRoles" class="form-label">用户角色</label>
                        <select multiple class="form-control" id="newRoles" required>
                            <option value="admin">超级管理员</option>
                            <option value="student">学生</option>
                            <option value="teacher">教师</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirmAddBtn" class="btn btn-primary">确认添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">修改用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId">
                    <div class="mb-3">
                        <label for="editUserName" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="editUserName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editPassword" class="form-label">密码</label>
                        <input type="password" class="form-control" id="editPassword">
                        <small class="form-text text-muted">留空表示不修改密码</small>
                    </div>
                    <div class="mb-3">
                        <label for="editSalt" class="form-label">盐值</label>
                        <input type="text" class="form-control" id="editSalt">
                        <small class="form-text text-muted">留空表示不修改盐值</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">是否锁定</label>
                        <div class="form-check form-switch">
                            <input type="checkbox" class="form-check-input" id="editLocked">
                            <label class="form-check-label" for="editLocked" id="editLockStatusLabel">未锁定</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editRoles" class="form-label">用户角色</label>
                        <select multiple class="form-control" id="editRoles" required>
                            <option value="admin">超级管理员</option>
                            <option value="student">学生</option>
                            <option value="teacher">教师</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirmEditBtn" class="btn btn-primary">确认修改</button>
            </div>
        </div>
    </div>
</div>

<!--动画小人-->
<div class="moving_img">
    <img ondragstart="return false;"
         oncontextmenu="return false;"
         src="https://patchwiki.biligame.com/images/blhx/e/e4/paog3n20ayfib617fxlvrowqt6ikfgm.png">
</div>
<script src="/moving.js"></script>
<script>
    $(document).ready(function() {

        function showToast(msg, type) {
            alert(type + ": " + msg);
        }

        $(document).on('change', '.lock-toggle', function() {
            const userId = $(this).data('id');
            const isChecked = $(this).is(':checked');
            const lockToggle = $(this);
            const statusLabel = $(this).next('label');

            $.ajax({
                url: `/system/updateLockStatus/${userId}`,
                method: 'POST',
                data: { locked: isChecked ? 1 : 0 }, // 传递锁定状态
                success: function(response) {
                    if (response.success) {
                        // 更新状态标签
                        statusLabel.text(isChecked ? '已锁定' : '未锁定');
                    } else {
                        showToast(response.message, 'error');
                        // 操作失败时恢复复选框状态
                        lockToggle.prop('checked', !isChecked);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('更新状态失败:', error);
                    showToast('网络错误，请重试', 'error');
                    // 网络错误时恢复复选框状态
                    lockToggle.prop('checked', !isChecked);
                },
                complete: function() {
                    // 无论成功失败，都恢复复选框可用状态
                    lockToggle.prop('disabled', false);
                }
            });
        });

        // 添加按钮点击事件 - 显示模态框
        $('#addBtn').click(function() {
            // 重置表单
            $('#addUserForm')[0].reset();
            // 重置锁定状态显示
            $('#newLocked').prop('checked', false);
            $('#lockStatusLabel').text('未锁定');
            // 显示模态框
            $('#addUserModal').modal('show');
        });

        // 确认添加按钮点击事件
        $('#confirmAddBtn').click(function() {
            const userName = $('#newUserName').val();
            const password = $('#newPassword').val();
            const salt = $('#newSalt').val();
            const locked = $('#newLocked').is(':checked') ? 1 : 0;
            const selectedRoles = Array.from($('#newRoles').val() || []);

            // 验证
            if (!userName || !password || selectedRoles.length === 0) {
                showToast('用户名、密码和角色为必填字段', 'error');
                return;
            }

            const userData = {
                userName: userName,
                password: password,
                salt: salt,
                locked: locked,
                roles: selectedRoles
            };

            $.ajax({
                url: '/system/addUser',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(response) {
                    if (response.success) {
                        showToast('用户添加成功', 'success');
                        $('#addUserModal').modal('hide');
                        location.reload();
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('添加用户失败:', error);
                    showToast('网络错误，请重试', 'error');
                }
            });
        });

        // 查询按钮点击事件
        $('#searchBtn').click(function() {
            location.reload();
        });

        // 批量删除按钮点击事件
        $('#batchDeleteBtn').click(function() {
            const selectedIds = [];
            $('.userCheckbox:checked').each(function() {
                selectedIds.push($(this).val());
            });
            if (selectedIds.length > 0) {
                if (confirm('确定要删除选中的用户吗？')) {
                    selectedIds.forEach(id => {
                        $.ajax({
                            url: `/users/${id}`,
                            method: 'DELETE',
                            success: function() {
                                location.reload();
                            },
                            error: function(error) {
                                console.error('删除用户失败:', error);
                            }
                        });
                    });
                }
            } else {
                alert('请选择要删除的用户');
            }
        });

        // 全选/反选
        $('#selectAll').change(function() {
            $('.userCheckbox').prop('checked', $(this).prop('checked'));
        });

        // 导出按钮点击事件
        $('#exportBtn').click(function() {
            const table = document.getElementById('userTable');
            const wb = XLSX.utils.table_to_book(table, { sheet: 'Sheet1' });
            XLSX.writeFile(wb, 'users.xls');
        });

        // 修改图标点击事件
        $(document).on('click', '.editIcon', function(e) {
            e.preventDefault();
            const userId = $(this).data('id');

            // 加载用户数据
            $.ajax({
                url: `/system/getUser/${userId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        const user = response.data;
                        // 填充表单
                        $('#editUserId').val(user.id);
                        $('#editUserName').val(user.userName);
                        $('#editLocked').prop('checked', user.locked === 1);
                        $('#editLockStatusLabel').text(user.locked === 1 ? '已锁定' : '未锁定');

                        // 填充角色选择
                        const selectElement = $('#editRoles');
                        selectElement.val([]); // 清空选择

                        // 选中已有的角色
                        if (user.userRoles && user.userRoles.length > 0) {
                            console.log('用户角色数据:', user.userRoles);

                            // 选中已有的角色
                            user.userRoles.forEach(userRole => {
                                // 确保userRole对象结构正确
                                if (userRole.id && userRole.name) {
                                    const roleName = userRole.name;
                                    console.log('尝试选中角色:', roleName);

                                    // 查找并选中匹配的选项
                                    const option = selectElement.find(`option[value="${roleName}"]`);
                                    if (option.length > 0) {
                                        option.prop('selected', true);
                                        console.log('成功选中角色:', roleName);
                                    } else {
                                        console.warn('未找到匹配的角色选项:', roleName);
                                    }
                                } else {
                                    console.error('角色数据结构不正确:', userRole);
                                }
                            });
                        } else {
                            console.log('用户没有分配角色');
                        }

                        // 显示模态框
                        $('#editUserModal').modal('show');
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取用户信息失败:', error);
                    showToast('网络错误，请重试', 'error');
                }
            });
        });

        // 确认修改按钮点击事件
        $('#confirmEditBtn').click(function() {
            const userId = $('#editUserId').val();
            const userName = $('#editUserName').val();
            const password = $('#editPassword').val();
            const salt = $('#editSalt').val();
            const locked = $('#editLocked').is(':checked') ? 1 : 0;
            const selectedRoles = Array.from($('#editRoles').val() || []);

            // 验证
            if (!userName || selectedRoles.length === 0) {
                showToast('用户名和角色为必填字段', 'error');
                return;
            }

            const userData = {
                id: userId,
                userName: userName,
                password: password !== '' ? password : null, // 密码为空表示不修改
                salt: salt !== '' ? salt : null, // 盐值为空表示不修改
                locked: locked,
                roles: selectedRoles
            };

            $.ajax({
                url: '/system/updateUser',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(response) {
                    if (response.success) {
                        showToast('用户修改成功', 'success');
                        $('#editUserModal').modal('hide');
                        location.reload();
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('修改用户失败:', error);
                    showToast('网络错误，请重试', 'error');
                }
            });
        });

        // 删除图标点击事件
        $(document).on('click', '.deleteIcon', function(e) {
            e.preventDefault();
            const userId = $(this).data('id');
            if (confirm('确定要删除该用户吗？')) {
                $.ajax({
                    url: `/users/${userId}`,
                    method: 'DELETE',
                    success: function() {
                        location.reload();
                    },
                    error: function(error) {
                        console.error('删除用户失败:', error);
                    }
                });
            }
        });
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>